<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>新闻详情页</title>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        body {
            font-family: "Microsoft Yahei", sans-serif;
            background-color: #f5f5f5;
            color: #333;
            padding-top: 60px; /* 为固定导航栏预留空间 */
        }
        .header {
            background-color: #407bff;
            padding: 15px 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            color: #fff;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            z-index: 100;
        }
        .header .logo {
            font-size: 18px;
            font-weight: bold;
        }
        .header .nav-buttons button {
            background-color: #fff;
            color: #407bff;
            border: none;
            padding: 8px 15px;
            margin-left: 10px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.3s ease;
        }
        .header .nav-buttons button:hover {
            background-color: #f0f7ff;
            transform: translateY(-2px);
        }
        .news-detail {
            max-width: 800px;
            margin: 20px auto;
            background-color: #fff;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
        }
        .news-title {
            font-size: 24px;
            text-align: center;
            margin-bottom: 15px;
        }
        .news-meta {
            text-align: center;
            color: #999;
            font-size: 14px;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 1px solid #eee;
        }
        .news-content {
            line-height: 1.8;
        }
        .news-image {
            width: 100%;
            height: 400px;
            margin-bottom: 20px;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        .news-image img {
            max-width: 100%;
            height: 100%;
        }
        /* 加载状态样式 */
        .loading {
            text-align: center;
            padding: 100px 0;
            color: #407bff;
        }
        .loading i {
            font-size: 24px;
            margin-right: 8px;
            animation: spin 1.5s linear infinite;
        }
        /* 错误状态样式 */
        .error {
            text-align: center;
            padding: 100px 0;
            color: #ff4d4f;
        }
        .error button {
            margin-top: 15px;
            padding: 8px 16px;
            background-color: #407bff;
            color: #fff;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }
        .error button:hover {
            background-color: #2a64e8;
        }
        @keyframes spin {
            from { transform: rotate(0deg); }
            to { transform: rotate(360deg); }
        }
    </style>
</head>

<body>
<div class="header">
    <div class="logo">01星球</div>
    <div class="nav-buttons">
        <button onclick="goToHome()"><i class="fa fa-home"></i> 返回首页</button>
        <button id="loginBtn" onclick="goToLogin()"><i class="fa fa-user"></i> 登录</button>
    </div>
</div>
<div class="news-detail" id="newsContainer">
    <!-- 内容将通过JavaScript动态加载 -->
    <div class="loading">
        <i class="fa fa-spinner"></i> 加载新闻详情中...
    </div>
</div>

<script>
    // 获取URL中的新闻ID
    function getNewsId() {
        const urlParams = new URLSearchParams(window.location.search);
        return urlParams.get('id');
    }

    // 加载新闻详情
    async function loadNewsDetail() {
        const newsId = getNewsId();
        const container = document.getElementById('newsContainer');///

        // 检查是否有新闻ID container.innerHTML渲染
        if (!newsId) {
            container.innerHTML = `
                <div class="error">
                    <p><i class="fa fa-exclamation-circle"></i> 无效的新闻ID</p>
                    <button onclick="goToHome()">返回首页</button>
                </div>
            `;
            return;
        }

        try {
            // 发起请求获取新闻详情
            const response = await fetch(`/news/${newsId}`);

            if (!response.ok) {
                throw new Error(`HTTP错误，状态码: ${response.status}`);
            }

            const result = await response.json();

            // 检查接口返回状态
            if (result.code !== 200) {
                throw new Error(result.message || '获取新闻失败');
            }

            const newsDetail = result.data;

            // 格式化日期（处理接口返回的ISO格式时间）
            const date = new Date(newsDetail.publishTime);
            const formattedDate = `${date.getFullYear()}年${(date.getMonth() + 1).toString().padStart(2, '0')}月${date.getDate().toString().padStart(2, '0')}日 ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;

            // 渲染新闻详情 文字和图片
            container.innerHTML = `
                <h1 class="news-title">${newsDetail.title}</h1>
                <p class="news-meta">
                    发布时间：${formattedDate}
                    &nbsp;&nbsp;作者：${newsDetail.author || '管理员'}
                    &nbsp;&nbsp;分类：${newsDetail.category}
                    <!-- &nbsp;&nbsp;浏览量：${newsDetail.viewCount} -->
                </p>
                ${newsDetail.picNew ? `
                    <div class="news-image">
                        <img src="${newsDetail.picNew}" alt="${newsDetail.title}相关图片">
                    </div>
                ` : ''}
                <div class="news-content">
                    ${newsDetail.content.replace(/\n/g, '<br><br>')}
                </div>
            `;

        } catch (error) {
            console.error('加载新闻详情失败:', error);
            container.innerHTML = `
                <div class="error">
                    <p><i class="fa fa-exclamation-circle"></i> 加载新闻详情失败: ${error.message}</p>
                    <button onclick="loadNewsDetail()">重试</button>
                    <button style="margin-left: 10px" onclick="goToHome()">返回首页</button>
                </div>
            `;
        }
    }

    // 页面跳转函数
    function goToHome() {
        window.location.href = "home.html";
    }

    function goToLogin() {
        window.location.href = "login.html";
    }

    // 检查用户登录状态
    function checkLoginStatus(){
        const token = localStorage.getItem('token');
        const loginBtn = document.getElementById('loginBtn');

        if (token) {
            // 如果用户已登录，显示退出登录按钮
            const username = localStorage.getItem('username') || '用户';
            loginBtn.innerHTML = `<i class="fa fa-sign-out"></i> 退出登录`;
            loginBtn.onclick = function() {
                if (confirm('确定要退出登录吗？')) {
                    localStorage.removeItem('token');
                    localStorage.removeItem('username');
                    location.reload();
                }
            };
        } else {
            // 如果用户未登录，显示登录按钮
            loginBtn.innerHTML = `<i class="fa fa-user"></i> 登录`;
            loginBtn.onclick = goToLogin;
        }

    }

    // html页面加载完成后执行 监听 确保了所有 HTML元素已存在于 DOM 中
    document.addEventListener('DOMContentLoaded', () => {
        loadNewsDetail();
        checkLoginStatus();
    });
</script>
</body>
</html>